package com.hj.ct.fragment;

import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMapTouchListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.hj.ct.R;
import com.hj.ct.activity.TableActivity;
import com.hj.ct.logic.GatherDataLogic;
import com.hj.ct.logic.LogicActions;
import com.hj.ct.logic.LoginLogic;
import com.hj.ct.model.CompositeData;
import com.hj.ct.model.SetAlarm;
import com.hj.ct.parse.GatherData;
import com.hj.ct.util.LogF;
import com.hj.ct.util.SetAlarmUtil;
import com.hj.ct.view.CustomDialog;

public class MapFragment extends BaseFragment {
	private final String TAG = MapFragment.class.getSimpleName();

	private MapView mMapView;
	private BaiduMap mBaiduMap;

	private CustomDialog dialog;
	private View rootView;

	private TableLayout mTableLayout;
	private View emptyView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_map, null);
		initView();
		rootView.findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				getActivity().finish();
			}
		});
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		registerHander();
	}

	public View findViewById(int id) {
		return rootView.findViewById(id);
	}

	private void initView() {
		emptyView = findViewById(R.id.emptyview);
		mTableLayout = (TableLayout) findViewById(R.id.tablelayout);
		mMapView = (MapView) findViewById(R.id.bmapView);
		mBaiduMap = mMapView.getMap();// 获取BaiduMap类 BaiduMap类才可以添加自定义的图层
		// mBaiduMap.setMyLocationEnabled(true);// 开启定位图层
		MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(9.0f);// 设置地图的缩放比例
		mBaiduMap.setMapStatus(msu);// 将前面的参数交给BaiduMap类

		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			@Override
			public boolean onMarkerClick(final Marker marker) {
				// 获得marker中的数据
				CompositeData data = (CompositeData) marker.getExtraInfo().get("data");
				// LatLng ll = marker.getPosition();
				showInfoWindow(data);
				return true;
			}
		});
		mBaiduMap.setOnMapTouchListener(new OnMapTouchListener() {

			@Override
			public void onTouch(MotionEvent arg0) {
				// TODO Auto-generated method stub
				mBaiduMap.hideInfoWindow();
			}
		});
		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

			@Override
			public void onMapStatusChangeStart(MapStatus arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onMapStatusChangeFinish(MapStatus arg0) {
				// TODO Auto-generated method stub
				mBaiduMap.hideInfoWindow();
			}

			@Override
			public void onMapStatusChange(MapStatus arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	// 弹出infoWindow
	private void showInfoWindow(final CompositeData data) {
		InfoWindow mInfoWindow;
		// 生成一个TextView用户在地图中显示InfoWindow
		TextView location = new TextView(getActivity().getApplicationContext());
		location.setBackgroundResource(R.drawable.icon_pop);
		location.setPadding(15, location.getPaddingTop(), 15, location.getPaddingBottom());
		location.setText(data.getDeviece().getDeviceName());
		location.setGravity(Gravity.CENTER);
		location.setTextColor(getResources().getColor(R.color.gray_808080));
		// 将marker所在的经纬度的信息转化成屏幕上的坐标
		LatLng ll = new LatLng(data.getDeviece().getLatitude(), data.getDeviece().getLongitude());
		Point p = mBaiduMap.getProjection().toScreenLocation(ll);
		LogF.d(TAG, "–!" + p.x + " , " + p.y);
		p.y -= 47;
		LatLng llInfo = mBaiduMap.getProjection().fromScreenLocation(p);
		mInfoWindow = new InfoWindow(location, llInfo, 0);
		location.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(data);
			}
		});
		// 显示InfoWindow
		mBaiduMap.showInfoWindow(mInfoWindow);
		// 将地图移到到最后一个经纬度位置
		moveMapToPoint(ll);
	}

	public static final int[] itemBgs = { R.drawable.list_selector_bg2, R.drawable.list_selector_bg };

	private void initTable(List<CompositeData> datas) {
		mTableLayout.removeAllViews();
		if (datas.isEmpty()) {
			emptyView.setVisibility(View.VISIBLE);
			return;
		} else {
			emptyView.setVisibility(View.GONE);
		}
		initBaseColum();
		Map<String, SetAlarm> alarmMaps = LoginLogic.getInstance().getSetAlarm();
		for (int i = 0; i < datas.size(); i++) {
			final CompositeData data = datas.get(i);
			TableRow row = new TableRow(getActivity());
			row.setBackgroundResource(itemBgs[i % 2]);
			row.setPadding(10, 15, 10, 15);
			row.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					showInfoWindow(data);
					showDialog(data);
				}
			});

			TextView tvName = new TextView(getActivity());
			TextView tvDust = new TextView(getActivity());
			TextView tvNoise = new TextView(getActivity());
			TextView tvWindSpeed = new TextView(getActivity());
			TextView tvWindDirection = new TextView(getActivity());
			GatherData gatherData = data.getGatherData();
			tvName.setText(data.getDeviece().getDeviceName());
			String dust = gatherData == null ? "-" : gatherData.getDustInst();
			String noise = gatherData == null ? "-" : gatherData.getLAFMaxPrf();
			String windSpeed = gatherData == null ? "-" : gatherData.getWindSP();
			String windDirection = gatherData == null ? "-" : gatherData.getWindDir();
			tvDust.setText("-".equals(dust) ? dust : dust + "mg/m³");// 粉尘
			tvNoise.setText("-".equals(noise) ? noise : noise + "db");// 噪声
			tvWindSpeed.setText(windSpeed);// 风速
			tvWindDirection.setText(windDirection);// 风向

			float warnDust =-1f;
			float warnNoise = -1f;
			SetAlarm alarm = alarmMaps.get(data.getDeviceId());
			if (alarm != null) {
				warnDust = SetAlarmUtil.getWarnDust(alarm);
			}
			if (alarm != null) {
				warnNoise =  SetAlarmUtil.getWarnNoise(alarm);
			}
			
			if (!"-".equals(dust) && warnDust > -1 && Float.valueOf(dust) >= warnDust) {
				tvDust.setTextColor(getResources().getColor(R.color.g_red));
			} else {
				tvDust.setTextColor(getResources().getColor(R.color.g_green));
			}
			if (!"-".equals(noise) && warnNoise > -1 && Float.valueOf(noise) >= warnNoise) {
				tvNoise.setTextColor(getResources().getColor(R.color.g_red));
			} else {
				tvNoise.setTextColor(getResources().getColor(R.color.g_green));
			}

			row.addView(tvName);
			row.addView(tvDust);
			row.addView(tvNoise);
			row.addView(tvWindSpeed);
			row.addView(tvWindDirection);
			mTableLayout.addView(row);
		}
	}

	private void initBaseColum() {
		TableRow baseRow = new TableRow(getActivity());
		baseRow.setBackgroundResource(R.color.gray_cccccc);
		baseRow.setPadding(10, 15, 10, 15);
		TextView tvTime = new TextView(getActivity());
		TextView tvDust = new TextView(getActivity());
		TextView tvNoise = new TextView(getActivity());
		TextView tvWindSpeed = new TextView(getActivity());
		TextView tvWindDirection = new TextView(getActivity());

		// 时间 粉尘浓度 噪声值 风速 风向
		tvTime.setText("名称");
		tvDust.setText("粉尘浓度");
		tvNoise.setText("噪声值");
		tvWindSpeed.setText("风速");
		tvWindDirection.setText("风向");

		baseRow.addView(tvTime);
		baseRow.addView(tvDust);
		baseRow.addView(tvNoise);
		baseRow.addView(tvWindSpeed);
		baseRow.addView(tvWindDirection);
		mTableLayout.addView(baseRow);
	}

	public void onPause() {
		// MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
		mMapView.onPause();
		super.onPause();
	}

	public void onResume() {
		// MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
		mMapView.onResume();
		super.onResume();
	}

	public void onDestroy() {
		// MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
		// mLocClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		if (mMapView != null) {
			mMapView.onDestroy();
			mMapView = null;
		}
		super.onDestroy();
	}

	/**
	 * 初始化图层
	 */
	private void addInfosOverlay(List<CompositeData> datas) {
		mBaiduMap.clear();
		LatLng latLng = null;
		OverlayOptions overlayOptions = null;
		Marker marker = null;
		BitmapDescriptor mIconMakerRed = BitmapDescriptorFactory.fromResource(R.drawable.marker_red);
		BitmapDescriptor mIconMakerGreen = BitmapDescriptorFactory.fromResource(R.drawable.marker_green);
		Map<String, SetAlarm> alarmMaps = LoginLogic.getInstance().getSetAlarm();
		for (CompositeData data : datas) {
			// 位置
			latLng = new LatLng(data.getDeviece().getLatitude(), data.getDeviece().getLongitude());
			// 图标
			
			float warnDust =-1f;
			float warnNoise = -1f;
			SetAlarm alarm = alarmMaps.get(data.getDeviceId());
			if (alarm != null) {
				warnDust = SetAlarmUtil.getWarnDust(alarm);
			}
			if (alarm != null) {
				warnNoise =  SetAlarmUtil.getWarnNoise(alarm);
			}
			
			GatherData gatherData = data.getGatherData();
			String dust = gatherData == null ? "-" : gatherData.getDustInst();
			String noise = gatherData == null ? "-" : gatherData.getLAFMaxPrf();
			boolean needWarn = false;
			if (!"-".equals(dust) && warnDust > -1 && Float.valueOf(dust) >= warnDust) {
				needWarn = true;
			} else if (!"-".equals(dust) && warnNoise > -1 && Float.valueOf(noise) >= warnNoise) {
				needWarn = true;
			}
			if (needWarn) {
				overlayOptions = new MarkerOptions().position(latLng).icon(mIconMakerRed).zIndex(5);
			} else {
				overlayOptions = new MarkerOptions().position(latLng).icon(mIconMakerGreen).zIndex(5);
			}
			marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
			Bundle bundle = new Bundle();
			bundle.putSerializable("data", data);
			marker.setExtraInfo(bundle);
		}
		// 将地图移到到最后一个经纬度位置
		moveMapToPoint(latLng);
	}

	private void moveMapToPoint(LatLng latLng) {
		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
		mBaiduMap.setMapStatus(u);
	}

	private void showDialog(final CompositeData data) {
		if (dialog == null) {
			dialog = new CustomDialog(getActivity());
			dialog.setOnlyOneBtn("详细数据");
		}
		dialog.setTitile(data.getDeviece().getDeviceName());
		dialog.setImageMessage(data.getDeviece().getImg(), R.drawable.icon_device_default);
		dialog.setOnlyOneBtnOnclickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(), TableActivity.class);
				intent.putExtra("data", data);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				dialog.dismiss();
				mBaiduMap.hideInfoWindow();
			}
		});
		dialog.show();
	}

	private void registerHander() {
		GatherDataLogic.getInstance().setRealDataHandler(this);
	}

	private void unregisterHander() {
		GatherDataLogic.getInstance().setRealDataHandler(null);
	}

	@Override
	public void handlerUI(int action, int code, Object... obj) {
		if (action == LogicActions.REAL_DATA_SUCCESS) {
			List<CompositeData> datas = (List<CompositeData>) obj[0];
			initTable(datas);
			addInfosOverlay(datas);
		} else if (action == LogicActions.NEED_TO_LOGIN) {
			showReLoginDialog();
		}
	}

	@Override
	public void onDetach() {
		unregisterHander();
		super.onDetach();
	}

}
